package server

import (
  "github.com/siddontang/go-log/log"
)

const (
  strSqlGetAllFamily = "SELECT `userid`,`name` FROM `user` WHERE `host`=1"
  strSqlGetFamily    = "SELECT `name` FROM `user` WHERE `hostname`=? AND `host`=0"

  strSqlGetNodeId = "SELECT `nodeid` FROM `node` WHERE `userid`=?"
)

func (app *App) LoadAllFamily() error {
  rows, err := app.db.Query(strSqlGetAllFamily)
  if err != nil {
    return err
  }
  defer rows.Close()

  var uuid, hostname string
  for rows.Next() {
    err = rows.Scan(&uuid, &hostname)
    if err != nil {
      return err
    }

    err = app.LoadFamily(hostname, uuid)
    if err != nil {
      return err
    }
  }
  return nil
}

func (app *App) LoadFamily(hostname string, uuid string) error {
  rows, err := app.db.Query(strSqlGetFamily, hostname)
  if err != nil {
    return err
  }
  defer rows.Close()

  // load host_user's info
  family, _ := dflFamilyMgr.NewFamily(hostname)
  family.uuid = uuid
  family.NewMember(hostname)
  log.Info("uuid: %s, familyname: %s, username: %s", family.uuid, family.name, hostname)

  // load all devices
  err = app.LoadAllNodeId(family)
  if err != nil {
    return err
  }

  // load other members' info
  var name string

  for rows.Next() {
    err = rows.Scan(&name)
    if err != nil {
      return err
    }
    family.NewMember(name)
    log.Info("uuid: %s, familyname: %s, username: %s", family.uuid, family.name, name)
  }
  return nil
}

func (app *App) LoadAllNodeId(family *Family) error {
  rows, err := app.db.Query(strSqlGetNodeId, family.uuid)
  if err != nil {
    return err
  }
  defer rows.Close()

  // get all nodeid
  var devname string
  var devinfo *Node

  for rows.Next() {
    err = rows.Scan(&devname)
    if err != nil {
      return err
    }
    devinfo, _ = family.NewDevice(devname)
    if devinfo == nil {
      break
    }
    log.Info("uuid: %s, familyname: %s, devname: %s", family.uuid, family.name, devname)
  }
  return nil
}
